package cpu.footprint.ui;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cpu.footprint.R;
import cpu.footprint.adapter.CommonAdapter;
import cpu.footprint.adapter.ViewHolder;
import cpu.footprint.api.ApiUrl;
import cpu.footprint.api.AppXUtilDao;
import cpu.footprint.api.MyApplication;
import cpu.footprint.api.ResultMessage;
import cpu.footprint.bean.Active;
import cpu.footprint.bean.BaseBean;
import cpu.footprint.bean.User;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.api.APIService;
import cpu.footprint.api.RespCallBack;
import cpu.footprint.popup.DoubleDatePickerDialog;
import cpu.footprint.util.CreateDialogUtil;
import cpu.footprint.util.FileUtil;
import cpu.footprint.util.UID;
import cpu.footprint.view.CustomGridView;

import static cpu.footprint.api.ApiUrl.URL_FILEPATH;

/**
 * Created by Administrator on 2017/3/25.
 */
@ContentView(R.layout.activity_createactive)
public class CreateActiveActivity extends BaseActivity {
    private String TAG = "CreateActiveActivity";
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    @ViewInject(R.id.edit_active_beginTime)
    private TextView edit_active_beginTime;
    @ViewInject(R.id.edit_active_endTime)
    private TextView edit_active_endTime;
    @ViewInject(R.id.edit_activeName)
    private EditText edit_activeName;
    @ViewInject(R.id.edit_activeactivitySite)
    private TextView edit_activeactivitySite;
    @ViewInject(R.id.edit_active_collectionSite)
    private EditText edit_active_collectionSite;
    @ViewInject(R.id.edit_active_personMaxNum)
    private EditText edit_active_personMaxNum;
    @ViewInject(R.id.edit_active_description)
    private EditText edit_active_description;
    @ViewInject(R.id.layout_images)
    private CustomGridView layout_images;
    private List<String> imgPaths = new ArrayList<>();//图片路径
    private CommonAdapter<String> imageAdapter;
    private User user = new User();
    private MyApplication myApplication;
    private Context mContext;
    private String imagePaths = "";//图片路径（用 ‘ ; ‘ 分隔）
    private double activityLongitude;//活动地点经度
    private double activityLatitude;//活动地点维度
    private String activeCity = "";
    private AppXUtilDao mAppXUtilDao = new AppXUtilDao();
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    private Dialog mDialog;
    private static final int REQUEST_CODE_PICK_IMAGE = 3;
    private static final int CROP_BIG_PICTURE = 13;
    private static final int TAKE_BIG_PICTURE = 14;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;
    //此App一些信息的存储文件夹路径
    private static final String appDirectoryPath = File.separator + "mnt" + File.separator + "sdcard" + File.separator + "footprint";
    Uri imageUri = Uri.parse(appDirectoryPath + "/picture.png");

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (mDialog != null) {
                if (mDialog.isShowing())
                    mDialog.dismiss();
            }
            switch (msg.what) {
                case ResultMessage.CREATE_ACTIVBE_SUCCESS: {
                    String json = msg.obj.toString();
                    String activeId = "";
                    String userId = "";
                    try {
                        JSONObject obj = new JSONObject(json);
                        activeId = obj.getInt("id") + "";
                        userId = obj.getInt("userId") + "";
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(CreateActiveActivity.this, ActiveDetailActivty.class);
                    intent.putExtra("activeId", activeId);
                    intent.putExtra("userId", userId);
                    startActivity(intent);
                    overridePendingTransition(0,R.anim.fade);
                    finish();
                    //CreateDialogUtil.ToastShow(mContext, msg.obj.toString());
                }
                break;
                case ResultMessage.CREATE_ACTIVBE_FAILED: {
                    CreateDialogUtil.ToastShow(mContext, msg.obj.toString());
                }
                break;
                case ResultMessage.UPLOAD_PICTURE_SUCCESS: {
                    imageAdapter.notifyDataSetChanged();
                    CreateDialogUtil.ToastShow(mContext, "上传成功");
                    imagePaths += msg.obj.toString() + ";";
                }
                break;
                case ResultMessage.UPLOAD_PICTURE_FAILED: {
                    CreateDialogUtil.ToastShow(mContext, msg.obj.toString());
                }
                break;
                case ResultMessage.FAILED:
                    CreateDialogUtil.ToastShow(mContext, "连接失败");
                    break;
                case ResultMessage.TIMEOUT:
                    CreateDialogUtil.ToastShow(mContext, "连接超时");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        InitView();
        myApplication = (MyApplication) this.getApplication();
        mContext = CreateActiveActivity.this;
        InitAdapter();
        if (myApplication.isLogin()) {
            user = myApplication.getUser();
        } else {
            Toast.makeText(CreateActiveActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(CreateActiveActivity.this, LoginActivity.class);
            intent.putExtra("IsLogin", false);
            startActivity(intent);
            overridePendingTransition(0,R.anim.fade);
            CreateActiveActivity.this.finish();
            return;
        }
    }

    private void InitView() {
        title_content.setText("添加活动");
        title_menu_image.setVisibility(View.GONE);
        title_menu_text.setVisibility(View.GONE);
        mDialog = showLoadingDialog(this);
        imgPaths.add("default.png");
        layout_images.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i == imgPaths.size()-1) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(CreateActiveActivity.this);
                    //    指定下拉列表的显示数据
                    final String[] cities = {"拍照", "相册"};
                    //    设置一个下拉的列表选择项
                    builder.setItems(cities, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case 0: {
                                    takePhone();
                                }
                                break;
                                case 1: {
                                    choosePhone();
                                }
                                break;
                            }
                        }
                    });
                    builder.show();
                }
            }
        });
    }

    @Event(value = {R.id.title_back, R.id.edit_active_beginTime, R.id.btn_createActive, R.id.edit_activeactivitySite, R.id.edit_active_endTime})
    private void OnClick(View v) {
        switch (v.getId()) {
            case R.id.title_back: {
                setResult(1);
                this.finish();
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            case R.id.edit_active_endTime: {
                Calendar c = Calendar.getInstance();
                // 最后一个false表示不显示日期，如果要显示日期，最后参数可以是true或者不用输入
                new DoubleDatePickerDialog(CreateActiveActivity.this, 0, new DoubleDatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                          int startDayOfMonth) {
                        edit_active_endTime.setText(String.format("%d-%d-%d", startYear, startMonthOfYear + 1, startDayOfMonth));
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), true, "开始日期").show();
            }
            break;
            case R.id.edit_active_beginTime: {
                Calendar c = Calendar.getInstance();
                // 最后一个false表示不显示日期，如果要显示日期，最后参数可以是true或者不用输入
                new DoubleDatePickerDialog(CreateActiveActivity.this, 0, new DoubleDatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear,
                                          int startDayOfMonth) {
                        edit_active_beginTime.setText(String.format("%d-%d-%d", startYear, startMonthOfYear + 1, startDayOfMonth));
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), true, "结束日期").show();
            }
            break;
            case R.id.edit_activeactivitySite: {
                Intent intent = new Intent(this, MapSerachActivity.class);
                startActivityForResult(intent, 1);
                overridePendingTransition(0,R.anim.fade);
            }
            break;
            case R.id.btn_createActive: {
                if (activityLongitude != 0 && activityLatitude != 0) {
                    CreateActive();
                } else {
                    CreateDialogUtil.ToastShow(mContext, "请选择活动地点");
                }
            }
            break;
            default:
                break;
        }
    }


    private void CreateActive() {
        String activeName = edit_activeName.getText().toString();
        String activeActivitySite = edit_activeactivitySite.getText().toString();
        String active_collectionSite = edit_active_collectionSite.getText().toString();
        String active_personMaxNum = edit_active_personMaxNum.getText().toString();
        String active_description = edit_active_description.getText().toString();
        String active_endTime = edit_active_endTime.getText().toString();
        String active_beginTime = edit_active_beginTime.getText().toString();
        Map<String, String> map = new HashMap<>();
        map.put("mobilePhone", user.getMobilePhone());
        map.put("token", user.getToken());
        map.put("name", activeName);
        map.put("province", activeCity);
        map.put("collectionSite", active_collectionSite);
        map.put("activitySite", activeActivitySite);
        map.put("beginTime", active_beginTime);
        map.put("endTime", active_endTime);
        map.put("personMaxNum", active_personMaxNum);
        map.put("activityLongitude",""+ activityLongitude);
        map.put("activityLatitude", ""+activityLatitude);
        map.put("description", active_description);
        try {
            imagePaths = imagePaths.substring(0, imagePaths.length() - 1);
        } catch (Exception e) {
        }
        map.put("imagePaths", imagePaths);
        mDialog.show();
        APIService.Post(ApiUrl.URL_CREATE_ACTIVE, map, new RespCallBack<BaseBean<Active>>(this) {
            @Override
            public void onSuccess(BaseBean<Active> result) {
                super.onSuccess(result);
                if(result.success){
                    Toast("创建活动成功!");
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mDialog.dismiss();
            }
        });

    }

    private void InitAdapter() {
        imageAdapter = new CommonAdapter<String>(this, imgPaths, R.layout.active_imgitem) {
            @Override
            public void convert(ViewHolder helper, String item, int position) {
                ImageView imageView = helper.getView(R.id.image);
                String fileName = URL_FILEPATH + item;
                if (FileUtil.fileIsExists(fileName)) {
                    Uri uri = Uri.fromFile(new File(fileName));
                    imageView.setImageURI(uri);
                } else {
                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.defaultpicture);
                    imageView.setImageBitmap(bitmap);
                }
            }
        };
        layout_images.setAdapter(imageAdapter);
        imageAdapter.notifyDataSetChanged();
    }

    /**
     * 重写后退函数
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            CreateActiveActivity.this.finish();
            overridePendingTransition(0,R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }

    /**
     * Activity回调函数
     *
     * @param req
     * @param res
     * @param data
     */
    public void onActivityResult(int req, int res, Intent data) {
        switch (req) {
            /**
             * 从相册中选取图片的请求标志
             */
            case REQUEST_CODE_PICK_IMAGE:
                if (res == Activity.RESULT_OK) {
                    try {
                        /**
                         * 该uri是上一个Activity返回的
                         */
                        imageUri = data.getData();
                        BeginUploadImage();
                        //cropImageUri(imageUri, 400, 400, CROP_BIG_PICTURE);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(this, "程序崩溃", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case TAKE_BIG_PICTURE://照相
                BeginUploadImage();
                break;
            case 1: {
                if (res == 1) {
                    try {
                        if (data.getStringExtra("activitySite") != null) {
                            edit_activeactivitySite.setText(data.getStringExtra("activitySite"));
                            double latitude = data.getDoubleExtra("latitude", 0);
                            double longitude = data.getDoubleExtra("longitude", 0);
                            activityLongitude = longitude;//活动地点经度
                            activityLatitude = latitude;//活动地点维度
                            activeCity = data.getStringExtra("activityCity");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            break;
            default:
                break;
        }
    }

    /**
     * 开始处理图片并上传
     */
    private void BeginUploadImage() {
        if (imageUri == null) {
            return;
        }
        Bitmap bitmap = decodeUriAsBitmap(imageUri);
        if (bitmap == null) {
            return;
        }
        DealWithPic(bitmap);
    }

    /**
     * 处理图片
     *
     * @param bitmap
     */
    private void DealWithPic(Bitmap bitmap) {
        if (bitmap == null) {
            return;
        }
        bitmap = FileUtil.imageZoom(bitmap);
        String fileName = UID.next() + ".png";
        FileUtil.saveMyBitmap(URL_FILEPATH + fileName, bitmap);
        imgPaths.remove(imgPaths.size() - 1);
        imgPaths.add(fileName);
        if(imgPaths.size()<9) {
            imgPaths.add("default.png");
        }
        imageAdapter.notifyDataSetChanged();
        Map<String, Object> map = new HashMap<>();
        map.put("mobilePhone", user.getMobilePhone());
        map.put("file", new File(URL_FILEPATH + fileName));
        map.put("token", user.getToken());
        mDialog.show();
        APIService.upLoadFile(ApiUrl.URL_UPLOAD_PICTURE, map, new RespCallBack<BaseBean<String>>(this) {
            @Override
            public void onSuccess(BaseBean<String> result) {
                super.onSuccess(result);
                if (result.success) {
                    Toast("上传成功!");
                    imagePaths += result.info + ";";
                } else {
                    Toast("上传失败!");
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                if (mDialog != null && mDialog.isShowing()) {
                    mDialog.dismiss();
                }
            }
        });
        bitmap.recycle();
    }

    public void choosePhone() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);

        } else {
            choosePhoto();
        }
    }

    /**
     * 拍照
     */
    void takePhoto() {
//        /**
//         * 最后一个参数是文件夹的名称，可以随便起
//         */
        File file = new File(Environment.getExternalStorageDirectory(), "footprint");
        if (!file.exists()) {
            file.mkdir();
        }
        /**
         * 这里将时间作为不同照片的名称
         */
        File output = new File(file, "head.jpg");
        try {
            if (output.exists()) {
                output.delete();
            }
            output.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**
         * 隐式打开拍照的Activity，并且传入CROP_PHOTO常量作为拍照结束后回调的标志
         */
        imageUri = Uri.fromFile(output);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//action is capture
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_BIG_PICTURE);//or TAKE_SMALL_PICTURE
        overridePendingTransition(0,R.anim.fade);
    }

    /**
     * 从相册选取图片
     */
    void choosePhoto() {
        /**
         * 打开选择图片的界面
         */
        File chooseImage = new File(appDirectoryPath, "head.jpg");
        if (chooseImage.exists())
            chooseImage.delete();
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                "image/*");
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE); //
        overridePendingTransition(0,R.anim.fade);
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @param outputX
     * @param outputY
     * @param requestCode
     */
    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, requestCode);
        overridePendingTransition(0,R.anim.fade);
    }

    private Bitmap decodeUriAsBitmap(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                takePhoto();
            } else {
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                choosePhoto();
            } else {
                // Permission Denied
                Toast.makeText(mContext, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 检查权限
     */
    public void takePhone() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE2);
        } else {
            takePhoto();
        }
    }
}
